package com.nononsenseapps.feeder.db.room

import androidx.paging.DataSource
import androidx.room.*
import cn.ekuma.odbo.mobile.room.BaseDao
import com.nononsenseapps.feeder.db.entity.FeedRule
import kotlinx.coroutines.flow.Flow

@Dao
interface FeedRuleDao: BaseDao<FeedRule> {

    @Query("SELECT * FROM feed_rule")
    fun listAll(): DataSource.Factory<Int, FeedRule>

    @Query("SELECT * FROM feed_rule where feed_id = :feedId or feed_id is NULL")
    fun listAllWithFeed(feedId:Long): DataSource.Factory<Int, FeedRule>

    @Query("SELECT * FROM feed_rule where feed_id = :feedId and able = :able")
    fun listWithFeed(feedId:Long,able : Boolean =true): List<FeedRule>

    @Query("SELECT * FROM feed_rule where feed_id IS NULL and able = :able")
    fun listGlobal(able : Boolean =true): List<FeedRule>

    @Query("SELECT * FROM feed_rule where id IS :feedRuleId")
    fun findFeedRuleById(feedRuleId : Long) : Flow<FeedRule>

    @Query("UPDATE  feed_rule set able = :able where id IS :id")
    fun updateFeedAble(id: Long, able: Boolean)
}

/**
 * Inserts or updates feed depending on if ID is valid. Returns ID.
 */
fun FeedRuleDao.upsert(feedRule: FeedRule): Long = when (feedRule.id > ID_UNSET) {
    true -> {
        update(feedRule)
        feedRule.id
    }
    false -> {
        val id=insert(feedRule)
        feedRule.id=id
        id
    }
}